package org.mcjug;

import oauth.signpost.OAuth;

import org.mcjug.model.YambaUtils;

import winterwell.jtwitter.Twitter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class StatusActivity extends BaseActivity {
	private static final String TAG = "StatusActivity";

	private int statusSize;

	private TextView titleTv;

	private TextView counterTv;

	private EditText statusEt;

	private Button updateButton;

	private LinearLayout mainLl;

	private Button resetTwitterButton;

	private SharedPreferences prefs;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		statusSize = getResources().getInteger(R.integer.max_characters);
		prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
		init();
		setContentView(mainLl);
		updateCounterTv(statusEt.getText());
	}

	private void init() {
		mainLl = new LinearLayout(getApplicationContext());
		mainLl.setOrientation(LinearLayout.VERTICAL);
		mainLl.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		mainLl.setBackgroundDrawable(getResources().getDrawable(R.drawable.cow));

		titleTv = new TextView(getApplicationContext());
		titleTv.setText(R.string.app_name);
		titleTv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		titleTv.setTextSize(30);

		counterTv = new TextView(getApplicationContext());
		LayoutParams counterTvLayoutParams = new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		counterTvLayoutParams.rightMargin = 10;
		counterTvLayoutParams.gravity = Gravity.RIGHT;
		counterTv.setLayoutParams(counterTvLayoutParams);

		statusEt = new EditText(getApplicationContext());
		statusEt.setLines(5);
		LayoutParams statusEtLayoutParams = new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		statusEtLayoutParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL;
		statusEtLayoutParams.weight = 1;
		statusEt.setGravity(Gravity.TOP);
		statusEt.setLayoutParams(statusEtLayoutParams);
		statusEt.setHint(R.string.statusactivity_status_text_initial_text);
		statusEt.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
				statusSize) });
		statusEt.setBackgroundColor(0xEE424242);
		statusEt.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			public void afterTextChanged(Editable s) {
				updateCounterTv(s);
			}
		});

		updateButton = new Button(getApplicationContext());
		updateButton.setText(R.string.statusactivity_update_button_text);
		updateButton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		updateButton.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				String status = statusEt.getText().toString();
				new PostToTwitter().execute(status);
				Log.d(TAG, "onClicked");
			}
		});

		resetTwitterButton = new Button(getApplicationContext());
		resetTwitterButton.setText("Reset Twitter");
		resetTwitterButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				final Editor edit = prefs.edit();
				edit.putString(OAuth.OAUTH_TOKEN, "");
				edit.putString(OAuth.OAUTH_TOKEN_SECRET, "");
				edit.commit();
			}
		});

		mainLl.addView(titleTv);
		mainLl.addView(counterTv);
		mainLl.addView(statusEt);
		mainLl.addView(updateButton);
		mainLl.addView(resetTwitterButton);
	}

	private void updateCounterTv(Editable s) {
		int count = statusSize - s.length();
		counterTv.setText(String.valueOf(count));
		counterTv.setTextColor(Color.GREEN);
		if (count < 20) {
			counterTv.setTextColor(Color.YELLOW);
		}

		if (count < 10) {
			counterTv.setTextColor(Color.RED);
		}
	}

	class PostToTwitter extends AsyncTask<String, Integer, String> {
		// Called to initiate the background activity
		@Override
		protected String doInBackground(String... statuses) {
			try {
				Twitter currentTwitter = ((YambaApplication) getApplication())
						.getTwitter();
				if (currentTwitter == null) {
					Log.d(TAG, "Twitter connection info not initialized");
					YambaUtils.broadcastNeedTwitterLogin(getApplicationContext());
					return "Twitter connection info not initialized";
				}
				currentTwitter.setStatus(statuses[0]);
			} catch (Throwable e) {
				e.printStackTrace();
				Log.e(TAG, e.toString());
				YambaUtils.broadcastNeedTwitterLogin(getApplicationContext());
				return "Failed posting twitter update";
			}

			return statuses[0];
		}

		// Called when there's a status to be updated
		@Override
		protected void onProgressUpdate(Integer... values) {

		}

		// Called once the background activity has completed
		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
					.show();
			statusEt.setText("");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

}